# -*- coding: utf-8 -*-
from qiniu import Auth, put_file, etag
import time
import os

def main():
    confs = get_conf()
    if confs is None:
        print("No config file for reading.")
    else:
        access_key,secret_key,bucket_name = confs[0].replace('\n',''),confs[1].replace('\n',''),confs[2]
        mysql_upload(access_key,secret_key,bucket_name)

def mysql_upload(access_key,secret_key,bucket_name):
    q = Auth(access_key, secret_key)
    time_str = time.strftime("%Y%m%d")
    file_name = "berry_sup_" + time_str + ".sql.tar.gz"
    up_file(file_name,q,bucket_name)

def oralce_upload(access_key,secret_key,bucket_name):
    q = Auth(access_key, secret_key)
    names = ["hssa","mangkhut"]
    for n in names:
        up_file(build_filename(n),q,bucket_name)

def get_conf():
    conf_path = os.path.split(os.path.realpath(__file__))[0] + os.sep + 'conf'
    fileos = open(conf_path,'r',encoding='utf-8')
    try:
        confs = fileos.readlines()
    except Exception as e:
        raise e
    finally:
        fileos.close()
        pass
    if confs is None or type(confs) != list or len(confs) != 3:
        return None
    return confs

def build_filename(str):
    time_str = time.strftime("%Y%m%d")
    return str + time_str + "db.dmp"

def up_file(file_name,q,bucket_name):
    token = q.upload_token(bucket_name, file_name, 3600)
    localfile = os.path.split(os.path.realpath(__file__))[0] + os.sep + file_name
    if not os.path.isfile(localfile):
        print(localfile," file not exist.")
        return
    ret, info = put_file(token, file_name, localfile)
    print(info)
    assert ret['key'] == file_name
    assert ret['hash'] == etag(localfile)

if __name__ == "__main__":
    main()
